/**
 * Created by 丶龟 on 2017/8/25.
 */

"use strict";

//=============
// 引入程序依赖
//=============
import React, { Component } from 'react' ;
import { connect } from 'react-redux' ;
import { Link, browserHistory } from 'react-router' ;

//交互依赖
import NetworkEngine from '../../utils/NetworkEngine' ;
import UrlManager from '../../utils/UrlManager' ;
import ErrorBar from "../../components/Public/ErrorBar/ErrorBar" ;

//images
import logo from "../../static/img/h5/logo.png";
import gantan from "../../static/img/h5/gantan.png";

class MobileModifyPswContainer2 extends Component{
    constructor(props){
        super(props) ;
        this.state = {
            phoneanhaohua : "",
            realPhone : '',
            showError: false,
            errorWord: '',
        }
    }
    componentWillMount(){
        this.anhaohua();
    }

    componentDidMount() {
        this.state.realPhone = this.props.params.id;
        this.state.clientIp = window.location.hostname;
        this.initGeetestFun();
    }

    //geetestAPI1
    initGeetestFun() {
        const _this = this;
        let urlManager = new UrlManager();
        NetworkEngine(
            "post",
            urlManager.initGeetest(),
            {
                userId: sessionStorage.getItem("id") ? sessionStorage.getItem("id") : "",
                clientType: "h5",
                clientIp: this.state.clientIp ? this.state.clientIp : null,
            }
        ).then(
            data => {
                let gtServerStatus = data.data.res.gt_server_status;
                let responseStr = data.data.res.responseStr;
                // let userId = data.data.res.userId;
                let geetestData = JSON.parse(responseStr);
                initGeetest({
                    gt: geetestData.gt,
                    challenge: geetestData.challenge,
                    new_captcha: geetestData.new_captcha, // 用于宕机时表示是新验证码的宕机
                    offline: !geetestData.success, // 表示用户后台检测极验服务器是否宕机，一般不需要关注
                    product: 'float',
                    width: "100%",
                    // bg_color:"custom",
                    // 更多配置参数请参见：http://www.geetest.com/install/sections/idx-client-sdk.html#config
                }, function (captchaObj) {
                    _this.state.captchaObj = captchaObj;
                    $("#submit1").click(function (e) {
                        //清空验证码及其错误信息
                        _this.refs.code.value = '';
                        $(_this.refs.wrongError).hide();
                        if (_this.state.resetCodeFlag === 1) {
                            captchaObj.reset();
                            _this.state.resetCodeFlag = 0;
                        } else {
                            _this.getyzm(captchaObj,gtServerStatus);
                        }
                    });
                    // 将验证码加到id为captcha的元素里，同时会有三个input的值用于表单提交
                    captchaObj.appendTo("#captcha1");

                    captchaObj.onReady(function () {
                        $("#wait1").hide();
                    });

                    captchaObj.onSuccess(function() {
                        //清空验证码及其错误信息
                        _this.refs.code.value = '';
                        $(_this.refs.wrongCode).hide();
                        _this.showErrorInfo("hide");
                    });
                });
            }
        ).catch(
            err => {

            }
        )
    }

    //展示极验证错误信息
    showErrorInfo(mes) {
        $(this.refs.wrongMessage).hide();
        if (mes === 'hide') {
            $(this.refs.wrongGeetest).hide();
        } else {
            $(this.refs.gtErrorMes).text(mes);
            $(this.refs.wrongGeetest).show();
        }
    }

    //校验电话号码
    anhaohua(){
        let phoneanhao = this.props.params.id;
        var regPhone = /\d{11}/g;
        phoneanhao = phoneanhao.replace(regPhone,function(word,index) {
            return word.substr(0,3) + "****" + word.substr(7,11);
        })
        this.setState({
            phoneanhaohua : phoneanhao,
        })
    }

    //获得验证码方法
    getyzm(captchaObj,gtServerStatus) {
        var verifyObj = captchaObj.getValidate();
        //验证不通过时
        if (!verifyObj) {
            this.showErrorInfo("请进行验证");
            return ;
        } else {
            //验证通过时,进入二次验证
            verifyObj.gtServerStatus = gtServerStatus;
            // this.verifyGeetestFun(result);
            if (this.state.resetCodeFlag === 0) {
                this.state.resetCodeFlag = 1;
            }
        }
        let param = {
            phone : this.state.realPhone,
            userId : sessionStorage.getItem("id") ? sessionStorage.getItem("id") : "",
            clientType : "h5",
            clientIp : this.state.clientIp ? this.state.clientIp : null,
            fnGeetestChallenge : verifyObj.geetest_challenge,
            fnGeetestValidate : verifyObj.geetest_validate,
            fnGeetestSeccode : verifyObj.geetest_seccode,
            gtServerStatus : verifyObj.gtServerStatus,

        };
        // 计数变量
        let urlManager = new UrlManager();
        NetworkEngine(
            "post",
            urlManager.getModifyPswSendCode(),param
        ).then(
            data => {
                let _data = data.data;
                if (_data.status === 0) {
                    //发送正确，修改按钮状态
                    this.changeBtn();
                } else if (_data.error_message && _data.status === 1) {
                    this.showErrorInfo(_data.error_message);
                } else if (_data.status === 2) {
                    this.state.captchaObj.reset();
                    this.showErrorInfo("极验证失败，请重新进行验证");
                }
            }
        )
        MtaH5.clickStat('ModifyPsw2_001');
    }

    //定时修改按钮状态
    changeBtn() {
        const _this= this;
        // 计数变量
        var t = 60;
        var time = setInterval(daojishi, 1000);
        // 获得按钮对象
        var getyzm = this.refs.yzm;

        function daojishi() {
            if (t > 0) {
                t--;
                getyzm.innerText = t + "秒" + "重新获取";
                getyzm.disabled = true;
            } else {
                getyzm.innerText = "重新获取";
                clearInterval(time);//清理定时器
                getyzm.disabled = false;
                //重新加载验证码标记置空
                _this.state.resetCodeFlag = 1;
            }
        }
    }

    // getyzm(){
    //     // 计数变量
    //     let urlManager = new UrlManager();
    //     NetworkEngine(
    //         "post",
    //         urlManager.getPhoneCode(),
    //         {
    //             "phone": this.props.params.id,
    //         }
    //     ).then(
    //         data => {
    //             let _data = data.data;
    //         }
    //     )
    //     var t = 60;
    //     var time = setInterval(daojishi,1000);
    //     // 获得按钮对象
    //     var getyzm = this.refs.yzm;
    //     function daojishi() {
    //         if (t > 0 ) {
    //             t --;
    //             getyzm.innerText = t + '秒' + '重新获取';
    //             getyzm.disabled = true;
    //         } else {
    //             getyzm.innerText = '重新获取';
    //             clearInterval(time);//清理定时器
    //             getyzm.disabled = false;
    //         }
    //     }
    // }

    checkCode(){
        let urlManager = new UrlManager();
        NetworkEngine(
            "post",
            urlManager.checkCode(),
            {
                "code":this.refs.code.value,
                "phone": this.props.params.id,
            }
        ).then(
            data => {
                let _data = data.data.data;
                if(_data==true) {
                    sessionStorage.setItem("modifyPswCode",this.refs.code.value);
                    browserHistory.push('/MobileModifyPsw3/'+this.props.params.id)
                }else{
                    $(this.refs.wrongError).show();
                }
            }
        )
    }

    //errorBar展示
    showErrorBar(messageWord){
        this.setState({showError:true,errorWord:messageWord});
        setTimeout(()=>{this.setState({showError:false,errorWord:''})},3000);
    }

    render(){
        return(
            <div className="login-form">
                <ErrorBar showError={this.state.showError} errorWord={this.state.errorWord}/>
                <div className="logo"><img src={logo} alt="咪吱logo"/></div>
                <div className="container">
                    <p className="username binding-p">找回密码的账号<span>{this.state.phoneanhaohua}</span><Link to="/MobileModifyPsw1" className="p-back">修改</Link></p>
                    <div className="form-geetest-item">
                        <div className="captcha">
                            <p id={"wait1"} className="show">正在加载验证码......</p>
                            <div id={"captcha1"}>
                            </div>
                        </div>
                        <div className="form-div-geetest">
                            <div className="form-wrong-geetest" ref="wrongGeetest">
                                <img className="wrong-img" src={gantan} alt="感叹"/>
                                <span className="wrong-geetest" ref="gtErrorMes">请点击进行验证</span>
                            </div>
                        </div>
                    </div>
                    <div className="input-f">
                        <div className="proving-f">
                            <input type="text" className="proving" ref="code" placeholder="手机验证码"/>
                            <button id="submit1"
                                    className="proving-btn"
                                    // onClick={this.getyzm.bind(this)}
                                    ref="yzm">获取验证码</button>
                        </div>
                        <div className="wrong" ref="wrongError">
                            <img src={gantan} alt="感叹"/>
                            <span ref="codeErrorMessage">验证码有误</span>
                        </div>
                    </div>
                    <button type="btn" onClick={this.checkCode.bind(this)} className="form-btn orange-btn">下一步</button>
                </div>
            </div>
        )
    }
}

const MobileModifyPsw2 = connect()(MobileModifyPswContainer2) ;

export { MobileModifyPsw2 as default } ;
